<?php
// 应用公共文件
use app\common\service\AuthService;
use think\facade\Cache;
use think\facade\Env;
use app\common\constants\CommonConstant;
use EasyAdmin\upload\Uploadfile;
use think\File;
use think\file\UploadedFile;
use think\facade\Db;
use think\facade\Log;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\admin\model\FigureSystem;
use app\admin\model\FigureUser;
use app\common\service\ApiV3Pay;
use app\admin\model\template\ConsumeSuccess;
use FFMpeg\FFMpeg;

function msg($data, $code, $msg = "", $count = null)
{
    return json([
        "code" => $code,
        "message" => $msg,
        "data" => $data,
        "count" => $count
    ]);
}

function result($errno, $message, $data = '')
{
    exit(json_encode(array(
        'errno' => $errno,
        'message' => $message,
        'data' => $data
    )));
}

function fieldexists($tablename, $fieldname)
{
    $isexists = Db::query("DESCRIBE " . $tablename . " `{$fieldname}`", array());
    return !empty($isexists) ? true : false;
}

function tableexists($table)
{
    if (!empty($table)) {
        $data = Db::query("SHOW TABLES LIKE '{$table}'", array());
        $rel_data = array();
        foreach ($data as $k => $v) {
            $data1 = array_values($v);
            $rel_data = array_merge($data1, $rel_data);
        }
        if (!empty($rel_data)) {
            $tablename = $table;
            if (in_array($tablename, $rel_data)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function consumerVerificationCode(){
    $VerificationCode  = getNonceStr(6);
    $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
    $consumerClaimLogInfo = $consumerClaimLogModel->where(['verification_code' =>$VerificationCode ])->find();
    if ($consumerClaimLogInfo){
        return consumerVerificationCode();
    }
    return  $VerificationCode;

}

function ticketCode(){
    $VerificationCode  = getNonceStr(6);
    $consumerClaimLogModel = new \app\admin\model\TicketOrder();
    $consumerClaimLogInfo = $consumerClaimLogModel->where(['code' =>$VerificationCode ])->find();
    if ($consumerClaimLogInfo){
        return consumerVerificationCode();
    }
    return  $VerificationCode;

}

function goodsCode(){
    $VerificationCode  = getNonceStr(6);
    $consumerClaimLogModel = new \app\admin\model\GoodsOrder();
    $consumerClaimLogInfo = $consumerClaimLogModel->where(['code' =>$VerificationCode ])->find();
    if ($consumerClaimLogInfo){
        return consumerVerificationCode();
    }
    return  $VerificationCode;

}
function getNonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}


function qr_code($id, $toUrl, $folder)
{
    $system = FigureSystem::where('id', 1)->find();

    $appid = $system['appid'];
    $secret = $system['appsecret'];

    if (empty($appid) || empty($secret)) {
        return "";
        exit();
    }

    $url_access_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
    $json_access_token = sendCmd($url_access_token, array());
    $arr_access_token = json_decode($json_access_token, true);
    $access_token = $arr_access_token['access_token'];
    $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
    $qrcode = array(
        'scene' => $id,
        'width' => 320,
        'page' => $toUrl
    );
    $result = sendCmd($url, json_encode($qrcode));

    $err_result = json_decode($result);

    if (isset($err_result->errcode)) {
        return $err_result->errmsg;
        exit();
    }

    $name = time() . rand(999, 9999);

    $path = root_path() . 'public/uploads/qr_code/' . $folder;

    if (!is_dir($path)) {
        mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
    }

    $path .= '/code-' . $name . '.png';

    $paths = request()->domain() . '/uploads/qr_code/' . $folder . '/code-' . $name . '.png';

    file_put_contents($path, $result);

    $file = new UploadedFile($path, $name . '.png');

    $upload = sysconfig('upload');

    $extension = "png";

    if (empty($upload['upload_type']) || $upload['upload_type'] == 'local') {
        $saveName = \think\facade\Filesystem::disk('public')->putFile('upload', $file);
        $domain = request()->domain();
        $img = $domain . "/" . $saveName;
        return $img;
    } elseif ($upload['upload_type'] == 'alioss') {

        $accesskey = $upload['alioss_access_key_id'];
        $secretkey = $upload['alioss_access_key_secret'];
        $bucket = $upload['alioss_bucket'];
        $domain = $upload['alioss_domain'];

        // 上传后保存的文件名
        $key = time() . mt_rand(999, 9999) . ".$extension";

        $ossClient = new \OSS\OssClient($accesskey, $secretkey, 'oss-accelerate.aliyuncs.com');
        $ossClient->uploadFile($bucket, $key, $path);

        $str = "https://" . $domain . "/" . $key;
        unlink($path);
        return $str;
    } elseif ($upload['upload_type'] == 'qnoss') {

        $accesskey = $upload['qnoss_access_key'];
        $secretkey = $upload['qnoss_secret_key'];
        $bucket = $upload['qnoss_bucket'];
        $domain = $upload['qnoss_domain'];

        // 上传后保存的文件名
        $key = time() . mt_rand(999, 9999) . ".$extension";
        $auth = new \Qiniu\Auth($accesskey, $secretkey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list ($ret, $err) = $uploadMgr->putFile($token, $key, $path);
        if ($err !== null) {
            return result(-1, '上传失败');
        } else {
            $str = $domain . "/" . $ret['key'];
            unlink($path);
            return $str;
        }
    } elseif ($upload['upload_type'] == 'txcos') {

        $accesskey = $upload['txcos_secret_id'];
        $secretkey = $upload['txcos_secret_key'];
        $bucket = $upload['txcos_bucket'];
        $domain = $upload['txcos_region'];

        // 上传后保存的文件名
        $key = time() . mt_rand(999, 9999) . ".$extension";

        $cosClient = new \Qcloud\Cos\Client([
            'region' => $domain,
            'schema' => "https",
            'credentials' => [
                'secretId' => $accesskey,
                'secretKey' => $secretkey
            ]
        ]);

        $result = $cosClient->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => $result
        ]);

        $str = "https://" . $bucket . ".cos." . $domain . ".myqcloud.com/" . $key;
        unlink($path);
        return $str;
    }
}


function sendCmd($url, $data)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Expect:'
    )); // 解决数据包大不能提交
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);
    }
    curl_close($curl); // 关键CURL会话
    return $tmpInfo; // 返回数据
}

function sysconfig($group, $name = null)
{
    $where = [
        'group' => $group
    ];
    $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
    if (empty($value)) {
        if (!empty($name)) {
            $where['name'] = $name;
            $value = \app\admin\model\SystemConfig::where($where)->value('value');
            Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
        } else {
            $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
            Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
        }
    }
    return $value;
}

function signToken($array)
{

    $key = config('app.token_key');

    $key_id = "key_id";

    $token = array(
        'iat' => time(), // 签发时间
        'nbf' => time(), // 开始生效时间
        'exp' => time() + 60 * 60 * 24, // token过期时间
        'data' => [
            'uid' => $array['uid'],
            'tenant_id' => $array['tenant_id']
        ]
    ); // 存储的用户信息

    $jwt = JWT::encode($token, $key, "HS256", $key);
    return $jwt;
}


function signUserToken($array,$expTime)
{

    $key = config('app.token_key');
    $token = array(
        'iat' => time(), // 签发时间
        'nbf' => time(), // 开始生效时间
        'exp' =>$expTime, // token过期时间
        'data' => [
            'uid' => $array['uid'],
        ]
    ); // 存储的用户信息

    $jwt = JWT::encode($token, $key, "HS256", $key);
    return $jwt;
}


function httpGet($url)
{
    // 初始化
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    // 执行后不直接打印出来
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // 不从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 执行并获取HTML文档内容
    $output = curl_exec($ch);

    // 释放curl句柄
    curl_close($ch);

    return $output;
}


function get_os()
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $os = false;

    if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
        $os = 'Windows 95';
    } elseif (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
        $os = 'Windows ME';
    } elseif (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
        $os = 'Windows 98';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
        $os = 'Windows Vista';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
        $os = 'Windows 7';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
        $os = 'Windows 8';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
        $os = 'Windows 10'; // 添加win10判断
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
        $os = 'Windows XP';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
        $os = 'Windows 2000';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
        $os = 'Windows NT';
    } elseif (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
        $os = 'Windows 32';
    } elseif (preg_match('/linux/i', $agent)) {
        $os = 'Linux';
    } elseif (preg_match('/unix/i', $agent)) {
        $os = 'Unix';
    } elseif (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'SunOS';
    } elseif (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'IBM OS/2';
    } elseif (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
        $os = 'Macintosh';
    } elseif (preg_match('/PowerPC/i', $agent)) {
        $os = 'PowerPC';
    } elseif (preg_match('/AIX/i', $agent)) {
        $os = 'AIX';
    } elseif (preg_match('/HPUX/i', $agent)) {
        $os = 'HPUX';
    } elseif (preg_match('/NetBSD/i', $agent)) {
        $os = 'NetBSD';
    } elseif (preg_match('/BSD/i', $agent)) {
        $os = 'BSD';
    } elseif (preg_match('/OSF1/i', $agent)) {
        $os = 'OSF1';
    } elseif (preg_match('/IRIX/i', $agent)) {
        $os = 'IRIX';
    } elseif (preg_match('/FreeBSD/i', $agent)) {
        $os = 'FreeBSD';
    } elseif (preg_match('/teleport/i', $agent)) {
        $os = 'teleport';
    } elseif (preg_match('/flashget/i', $agent)) {
        $os = 'flashget';
    } elseif (preg_match('/webzip/i', $agent)) {
        $os = 'webzip';
    } elseif (preg_match('/offline/i', $agent)) {
        $os = 'offline';
    } else {

        $os = '未知操作系统';
    }
    return $os;
}
function get_broswer()
{
    $sys = $_SERVER['HTTP_USER_AGENT']; // 获取用户代理字符串
    if (stripos($sys, "Firefox/") > 0) {
        preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
        $exp[0] = "Firefox";
        $exp[1] = $b[1]; // 获取火狐浏览器的版本号
    } elseif (stripos($sys, "Maxthon") > 0) {
        preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
        $exp[0] = "傲游";
        $exp[1] = $aoyou[1];
    } elseif (stripos($sys, "MSIE") > 0) {
        preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
        $exp[0] = "IE";
        $exp[1] = $ie[1]; // 获取IE的版本号
    } elseif (stripos($sys, "OPR") > 0) {
        preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
        $exp[0] = "Opera";
        $exp[1] = $opera[1];
    } elseif (stripos($sys, "Edge") > 0) {
        // win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
        preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
        $exp[0] = "Edge";
        $exp[1] = $Edge[1];
    } elseif (stripos($sys, "Edg") > 0) {
        // 新Edge浏览器
        preg_match("/Edg\/([\d\.]+)/", $sys, $Edg);
        $exp[0] = "Edg";
        $exp[1] = $Edg[1];
    } elseif (stripos($sys, "Chrome") > 0) {
        preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
        $exp[0] = "Chrome";
        $exp[1] = $google[1]; // 获取google chrome的版本号
    } elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
        preg_match("/rv:([\d\.]+)/", $sys, $IE);
        $exp[0] = "IE";
        $exp[1] = $IE[1];
    } else {
        $exp[0] = "unknown";
        $exp[1] = "";
    }
    return $exp[0] . '(' . $exp[1] . ')';
}

function get_device()
{
    $device = false;
    $user_agent = $_SERVER['HTTP_USER_AGENT']; // 获取用户代理字符串
    if (stristr($user_agent, 'iPad')) {
        $device = 'iPad';
    } elseif (stristr($user_agent, 'Android')) {
        $device = 'Android';
    } elseif (stristr($user_agent, 'Linux')) {
        $device = 'Linux';
    } elseif (stristr($user_agent, 'iPhone')) {
        $device = 'iPhone';
    } else {
        $device = 'PC';
    }
    return $device;
}

function getPayNo($text ='')
{
    return $text . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
function MakeSign($array, $key)
{
    // 签名步骤一：按字典序排序参数
    ksort($array);
    $string = ToUrlParams($array);
    // 签名步骤二：在string后加入KEY
    $string = $string . "&key=" . $key;
    // 签名步骤三：MD5加密
    $string = md5($string);
    // 签名步骤四：所有字符转为大写
    $result = strtoupper($string);
    return $result;
}
function ToUrlParams($arr)
{
    $buff = "";
    foreach ($arr as $k => $v) {
        if ($k != "sign" && $v != "" && !is_array($v)) {
            $buff .= $k . "=" . $v . "&";
        }
    }
    $buff = trim($buff, "&");
    return $buff;
}
function FromXml($xml)
{
    // 将XML转为array
    // 禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $arr;
}

if (!function_exists('wtw_request')) {

    /**
     * 请求接口
     *
     * @param unknown $url
     * @param string $data
     * @return mixed
     */
    function wtw_request($url, $data = null)
    {
        $userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $info = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            print_r($info);
            print_r(curl_getinfo($curl));
            // echo 'Errno:'.curl_getinfo($curl);//捕抓异常
            // dump(curl_getinfo($curl));
        }
        return $info;
    }
}
function ToXml($array)
{
    $xml = "<xml>";
    foreach ($array as $key => $val) {
        if ($key != 'body') {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}
function sign_pay($arr, $appid, $pay_key)
{
    $package = "prepay_id=" . $arr['prepay_id'];
    $signType = "MD5";
    $time = (int)time();
    $array = array(
        'appId' => $appid,
        'nonceStr' => $arr['nonce_str'],
        'package' => $package,
        'signType' => $signType,
        'timeStamp' => (string)$time
    );
    $sign_str = MakeSign($array, $pay_key);

    $array['paySign'] = $sign_str;
    return $array;
}
 function httpRequest($url, $data, $header =[])
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//$header以array格式
    }

    $response = curl_exec($curl); // 执行操作

    if (curl_errno($curl)) {
        echo 'Error:' . curl_error($curl);//捕抓异常
    }

    curl_close($curl); // 关闭CURL会话
    return $response; // 返回数据，json格式



}

function common_qr_code($url, $folder,$platform_id)
{

    require_once(root_path() . "vendor/phpqrcode/qrlib.php");

    $errorCorrectionLevel = "L";
    $matrixPointSize = "6.3";
    $margin = "1";
    $name = time() . rand(999, 9999);

    $path = root_path() . 'public/uploads/qr_code/' . $folder;

    if (!is_dir($path)) {
        mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
    }
    $path .= '/code-' . $name . '.png';
     \QRcode::png($url, $path, $errorCorrectionLevel, $matrixPointSize, $margin);


    $platformUploadModel   = new \app\admin\model\PlatformUpload();
    $platformUploadModelInfo = $platformUploadModel->where(['id' => $platform_id])->find();

   if ($platformUploadModelInfo){
       $file = new UploadedFile($path, $name . '.png');
       if ($platformUploadModelInfo['upload_type'] ='local'){
           $saveName = \think\facade\Filesystem::disk('public')->putFile('upload', $file);
           $domain = request()->domain();
           $img = $domain . "/" . $saveName;
           return $img;
       }elseif($platformUploadModelInfo['upload_type'] ='alioss'){
           $extension = "png";
           $accesskey = $platformUploadModelInfo['alioss_access_key_id'];
           $secretkey = $platformUploadModelInfo['alioss_access_key_secret'];
           $bucket = $platformUploadModelInfo['alioss_bucket'];
           $domain = $platformUploadModelInfo['alioss_domain'];

           // 上传后保存的文件名
           $key = time() . mt_rand(999, 9999) . ".$extension";

           $ossClient = new \OSS\OssClient($accesskey, $secretkey, 'oss-accelerate.aliyuncs.com');
           $ossClient->uploadFile($bucket, $key, $path);

           $str = "https://" . $domain . "/" . $key;
           unlink($path);
           return $str;
       } elseif ($platformUploadModelInfo['upload_type'] == 'qnoss') {
           $extension = "png";
           $accesskey = $platformUploadModelInfo['qnoss_access_key'];
           $secretkey = $platformUploadModelInfo['qnoss_secret_key'];
           $bucket = $platformUploadModelInfo['qnoss_bucket'];
           $domain = $platformUploadModelInfo['qnoss_domain'];

           // 上传后保存的文件名
           $key = time() . mt_rand(999, 9999) . ".$extension";

           $auth = new \Qiniu\Auth($accesskey, $secretkey);
           // 生成上传 Token
           $token = $auth->uploadToken($bucket);
           // 初始化 UploadManager 对象并进行文件的上传
           $uploadMgr = new \Qiniu\Storage\UploadManager();
           // 调用 UploadManager 的 putFile 方法进行文件的上传
           list ($ret, $err) = $uploadMgr->putFile($token, $key, $path);
           if ($err !== null) {
               return result(-1, '上传失败');
           } else {
               $str = $domain . "/" . $ret['key'];
               unlink($path);
               return $str;
           }
       }
   }else{
       $file = new UploadedFile($path, $name . '.png');
       $saveName = \think\facade\Filesystem::disk('public')->putFile('upload', $file);
       $domain = request()->domain();
       $img = $domain . "/" . $saveName;
       return $img;

   }


}


function jsonPost($url, $header, $data = NULL)
{

    $headers = array(
        'Content-Type: application/json; charset=utf-8'
    );
    if (!empty($header)) {
        $headers = array_merge($headers, $header);
    }

    // 模拟提交数据函数
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在

    curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 600); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 类型为json
    $result = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Error POST' . curl_error($curl);
    }
    curl_close($curl); // 关键CURL会话
    return $result; // 返回数据
}


function getAccessToken($appid,$appsecret)
{


    $access_token = "";



        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;

        $res = json_decode(wtw_request($url), true);

        if (!empty($res) && !empty($res['access_token'])) {
            $access_token = $res['access_token'];
        }
    return $access_token;
}
